package com.squirrel.serialportcore.machine.init.before;

import com.squirrel.serialportcore.common.CommonBase;
import gnu.io.CommPortIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Enumeration;
import java.util.Map;

/**
 * 获取所有端口 过滤串口 并开启
 * 该初始化方法应该在spring初始化之前嵌入
 * 以影响 PortBase.SerialPortsIdentifier
 *
 * @author Squbi
 * @date 2021/3/23 9:43
 */
public class CommPortInitializer {
    private static final Logger logger = LoggerFactory.getLogger(CommPortInitializer.class);

    private CommPortInitializer() {
    }

    public static void initIdentifier() {
        Map<String, CommPortIdentifier> serialPortsIdentifier = CommonBase.getSerialPortsIdentifier();
        Enumeration<?> commPortList = CommPortIdentifier.getPortIdentifiers();
        while (commPortList.hasMoreElements()) {
            //获取该通信接口的信息 如果是串口储存
            CommPortIdentifier cpi = (CommPortIdentifier) commPortList.nextElement();
            if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                serialPortsIdentifier.put(cpi.getName(), cpi);
            }
        }
        logger.info(" 串口扫描完成 {}", serialPortsIdentifier.keySet());
    }
}
